package com.pencilisland.pay.core.mp.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.constant.OrderConstant;
import com.pencilisland.pay.api.bean.mp.core.MessageRequest;
import com.pencilisland.pay.api.bean.mp.core.MessageResponse;
import com.pencilisland.pay.api.bean.mp.core.WxTemplateREQ;
import com.pencilisland.pay.api.bean.mp.core.WxTemplateRES;
import com.pencilisland.pay.api.bean.wxpay.WxTemplate;
import com.pencilisland.pay.api.entity.TradeOrderEntity;
import com.pencilisland.pay.api.repository.TradeOrderRepository;
import com.pencilisland.pay.core.mp.service.MBService;
import com.pencilisland.pay.core.service.WxappService;
/**
* 报文逻辑处理.发送微信模板消息 
*
* @author breeze
*/
@Service("MB_wxTemplate")
public class  WxTemplateMB implements MBService {

	@Autowired
	ObjectMapper objectMapper;
	
	@Autowired
	TradeOrderRepository tradeOrderRepo;
	
	@Autowired
	WxappService wxappService;

	@Override
	public MessageResponse process(MessageRequest request) {
		WxTemplateREQ requestBean = getRequestBody(request);
		
		TradeOrderEntity tradeOrder = tradeOrderRepo.findOne(requestBean.getOrderNo());
		
		if(tradeOrder!=null){
			//发送推送模板消息
			WxTemplate wxTemplate = new WxTemplate();
			wxTemplate.setToUser(tradeOrder.getOpenId());
			wxTemplate.setFormId(requestBean.getFormId());
			wxTemplate.setTemplateId(OrderConstant.PAY_TEMPLATE_ID);
			Map<String,Object> data = new HashMap<String,Object>();
			wxTemplate.setData(data);
			wxappService.sendTemplate(wxTemplate);
		}
		
		WxTemplateRES res= new WxTemplateRES(true,null,"OK");
		return res;
	}
	
	public WxTemplateREQ getRequestBody(MessageRequest request){
		return objectMapper.convertValue(request.getBody(), WxTemplateREQ.class);
	}

}
